﻿using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Common
{
    public static class Serializer
    {
        private static readonly object WriteLock = new object();

        public static bool TrySerialize<T>(T source, string path)
        {
            lock (WriteLock)
            {
                if (Equals(source, default(T))) return false;
                FileStream fs = null;
                try
                {
                    if (string.IsNullOrEmpty(path)) return false;
                    string directoryPath = Path.GetDirectoryName(path);
                    if (string.IsNullOrEmpty(directoryPath)) return false;
                    if (!Directory.Exists(directoryPath)) Directory.CreateDirectory(directoryPath);
                    fs = new FileStream(path, FileMode.Create);
                    var bf = new BinaryFormatter();
                    fs.Position = 0;
                    bf.Serialize(fs, source);
                    return true;
                }
                catch
                {
                    return false;
                }
                finally
                {
                    if (fs != null)
                    {
                        fs.Flush();
                        fs.Close();
                    }
                }
            }
        }

        public static T TryDesSerialize<T>(string path)
        {
            FileStream fs = null;
            try
            {
                if (!File.Exists(path)) return default(T);
                fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
                BinaryFormatter bf = new BinaryFormatter();
                fs.Position = 0;
                return (T)bf.Deserialize(fs);
            }
            catch
            {
                return default(T);
            }
            finally
            {
                if (fs != null) fs.Close();
            }
        }
    }
}
